package http_client

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"time"

	"github.com/pkg/errors"
	"github.com/spf13/cast"
)

func Do(ctx context.Context, requestURL, method string, headers, params map[string]string, body interface{}, timeout time.Duration) ([]byte, error) {
	clinet := http.Client{
		Timeout: timeout,
	}
	data, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	request, err := http.NewRequest(method, requestURL, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json")
	for key, value := range headers {
		request.Header.Set(key, value)
	}
	pparams := make(url.Values)
	for key, value := range params {
		pparams.Add(key, value)
	}
	request.URL.RawQuery = pparams.Encode()
	resp, err := clinet.Do(request)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("http status:" + cast.ToString(resp.StatusCode))
	}
	defer resp.Body.Close()
	return io.ReadAll(resp.Body)
}
